package com.laicunba.ext.web.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.laicunba.util.SessionUtil;

@Component
public class CommSpringFilter implements HandlerInterceptor {
	private static final Logger LOG = Logger.getLogger(CommSpringFilter.class);
	private static ThreadLocal<Long> timestamp = new ThreadLocal();

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		timestamp.set(System.currentTimeMillis());
		SessionUtil.RID.set(Long.toString(System.currentTimeMillis()));
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		LOG.info(String.format("[rid:%s,uid:%s,tag:AFTER_COMPLETION,time:%s,ip:%s]\t%s\t%s", SessionUtil.RID.get(), SessionUtil.CURRENT_USER_ID.get(), System.currentTimeMillis() - timestamp.get(), request.getHeader("X-Real-IP"), request.getRequestURI(),
				JSONObject.fromObject(request.getParameterMap()).toString()));
		SessionUtil.RID.remove();
		timestamp.remove();

	}

}
